﻿package com.sos.utils {
	
	import com.deadreckoned.assetmanager.AssetManager;
	import com.deadreckoned.assetmanager.events.AssetEvent;
	import com.sos.Application;
	import com.sos.config.Configuration;
	import com.sos.core.cards.Card;
	import com.sos.core.game.client.GameClient;
	import com.sos.core.game.client.GameClientOptions;
	import com.sos.core.game.engine.events.GameEngineEvent;
	import com.sos.core.game.engine.GameEngine;
	import com.sos.core.game.events.GameEvent;
	import com.sos.core.game.GamePlayerCard;
	import com.sos.core.game.GameStatus;
	import com.sos.core.Player;
	import com.sos.ui.LoginPanel;
	import com.sos.ui.PlayArea;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.system.System;
	import com.sos.core.cards.CardManager;
	import com.sos.core.cards.CardType;
	import com.sos.logging.Logger;
	import flash.display.LoaderInfo;
	
	
	
	public class Initializer extends MovieClip
	{
		public var _assetManager:AssetManager;
		public var _cardImageList:Array = new Array();
		public var _playerImageList:Array = new Array();
		public var mainStage:DisplayObject;
		public var loadingText:TextField;
		public var playArea:PlayArea;
		public var currentStatus:GameStatus;
		
		public var gameEngine:GameEngine;
		public var gameClient:GameClient;
		
		public var currentGameId:uint;
		private var currentGameTxt:String;
		private var playerPassword:String;
		private var playerID:uint;
		private var username:String;
		private var loginPanel:LoginPanel;
		
		public function Initializer(mainStage:DisplayObject, testData:Array):void
		{
			// Turn verbose mode on/off
			//AssetManager.verbose = false;
			
			var localTesting:Boolean = testData['localTest'];
			this.mainStage = mainStage;
			
			loadingText = new TextField();
			loadingText.width = 450;
			loadingText.type = TextFieldType.DYNAMIC;
			//loadingText.border = true;
			loadingText.x = 10;
			loadingText.y = 10;
			loadingText.multiline = true;
			loadingText.wordWrap = true;
			
			MovieClip(mainStage).addChild(loadingText);
			
			// Setup asset manager
			_assetManager = AssetManager.getInstance();
			_assetManager.addEventListener(AssetEvent.QUEUE_START, onQueueStart, false, 0, true);
			_assetManager.addEventListener(AssetEvent.QUEUE_COMPLETE, onQueueComplete, false, 0, true);
			_assetManager.localTesting = localTesting;
			
			//Connect to game client
			
			currentGameTxt = '';
			
			username = testData['usr'];
			playerPassword = testData['pwd'];
			currentGameTxt = testData['gameId'];
			
			var loadGame:Boolean = false;
			if (username != '' && playerPassword != '' && currentGameTxt != '')
				loadGame = true;
			
			loginPanel = new LoginPanel();
			loginPanel.x = 310;
			loginPanel.y = 185;
			loginPanel.pwdTxt.displayAsPassword = true;
			loginPanel.usernameTxt.text = username;
			loginPanel.pwdTxt.text = playerPassword;
			loginPanel.gameTxt.text = currentGameTxt;
			
			loginPanel.loginButton.textLabel.text = 'Login';
			
			loginPanel.loginButton.buttonMode = true;
			loginPanel.loginButton.useHandCursor = true;
			loginPanel.loginButton.mouseChildren = false;
			MovieClip(mainStage).addChild(loginPanel);
			loginPanel.loginButton.addEventListener(MouseEvent.CLICK, loginButtonClickHandler);
			
			Application.instance.init(Configuration.getDefault());
						
			addEventListener(Event.ENTER_FRAME, memCheck);
			loadingText.addEventListener(MouseEvent.CLICK, shutdown);
			
			if (loadGame == true) {
				loginPanel.loginButton.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
			}
		}
		
		private function shutdown(e:MouseEvent):void {
			MovieClip(mainStage).removeChild(playArea);
			playArea.dispose();
			playArea = null;
			loginPanel.visible = true;
		}
		
		private function memCheck(e:Event):void {
			loadingText.text = "MEMORY CHECK: " +  System.totalMemory + "\n";
		}
		
		private function loginButtonClickHandler(e:MouseEvent):void {
			
			loginPanel.visible = false;
			
			username = loginPanel.usernameTxt.text;
			playerPassword = loginPanel.pwdTxt.text;
			currentGameId = uint(loginPanel.gameTxt.text);
			
			trace("GameId: " + currentGameId + " txt: " + loginPanel.gameTxt.text);
			
			Application.instance.login(username, playerPassword, loginOkHandler, loginFailedHandler);
		}
		
		
		private function loginOkHandler():void {
			
			playerID = Application.instance.user.id;
			var clientOptionsJson:String = '{"params":{"gameID":' + currentGameId + ',"userID": ' + playerID + ',"password":"'+ playerPassword +'"}}';
			var clientOptionsObj:Object = JsonUtils.decode(clientOptionsJson);
			gameClient = new GameClient(new GameClientOptions(clientOptionsObj));
			gameEngine = new GameEngine(gameClient, Application.instance.config.gameOptions);
			
			gameEngine.addEventListener(GameEvent.EVENT_GAME_RESTART, gameStartHandler);
			gameEngine.addEventListener(GameEvent.EVENT_GAME_START, gameStartHandler);
			
			gameEngine.addEventListener(GameEngineEvent.EVENT_GAME_ENGINE_START, gameEngineStartHandler);
			
			gameEngine.start();
			
		}
		
		private function gameEngineStartHandler(e:GameEngineEvent):void {
			var opponent = new Player( { username: "Test Engine Opponent (id:3)" } );
			gameEngine.forceStartPlaying(Application.instance.user, opponent, Application.instance.collection.activeDeck, currentGameId);
		}
		
		private function gameStartHandler(e:GameEvent):void {
			
			 var cardManager:CardManager = CardManager.getCardManager();
			 var card:Card;
			 
			 Logger.debug("INITIALIZER > CardManager has " + cardManager.count + " cards");
			 
			 for (var i:uint = 0; i < cardManager.count; i++) {
				 
				 card = cardManager.getCard(i);
				 if (card.type == CardType.ACTION) 
					_cardImageList.push(card.image);
				 else if (card.type == CardType.PLAYER || card.type == CardType.GOALKEEPER)
					_playerImageList.push(card.image);
				 
			 }
			
			_cardImageList.push('ACBlank');
			
			var ciListLength:Number = _cardImageList.length;
			var assetManagerOptions:Object = new Object();
			for (i = 0; i < ciListLength; i++) {
				assetManagerOptions.id = _cardImageList[i];
				if (!_assetManager.contains(_cardImageList[i])) {
					_assetManager.add('img/actionCards/' + _cardImageList[i] + '.gif', assetManagerOptions);
				}
				
			}
			var piListLength:Number = _playerImageList.length;
			
			for (i = 0; i < piListLength; i++) {
				assetManagerOptions.id = "s_" + _playerImageList[i];
				if (!_assetManager.contains(_playerImageList[i])) {
					_assetManager.add('img/players/small_' + _playerImageList[i] + '.gif', assetManagerOptions);
					assetManagerOptions.id = _playerImageList[i];
					_assetManager.add('img/players/' + _playerImageList[i] + '.gif', assetManagerOptions);
				}
			}
			_assetManager.load();
		}
		
		
		private function loginFailedHandler(msg:String):void {
			trace("Login Failed:", msg);
		}
		
		public function initUI() {
			
			//MovieClip(mainStage).gotoAndPlay(2);
			playArea = new PlayArea();
			MovieClip(mainStage).addChild(playArea);
			
			
			playArea.init(gameEngine);
			playArea.password = playerPassword;
			//addEventListener(GameEvent.EVENT_GAME_NEXT_TURN_PHASE, phaseChangeHandler);
			currentStatus = GameStatus.PLAY;
			
			//TESTING ACTIONS
			
		}
		
		/******************************************************** LISTENERS *************************************************************************/
		
		
		/**
		 * Executed when the asset queue begins loading.
		 * @param	e	The AssetEvent object
		 */
		private function onQueueStart(e:AssetEvent):void
		{
			trace("--------------------------");
			trace("Master asset queue started");
			trace("--------------------------");
			
			loadingText.htmlText += "Master asset queue started<br>";
		}
		
		/**
		 * Executed when all assets in the queue have completed loading.
		 * @param	e	The AssetEvent object
		 */
		private function onQueueComplete(e:AssetEvent):void
		{
			trace("---------------------------");
			trace("Master asset queue complete");
			trace("---------------------------");
			
			loadingText.htmlText += "Master asset queue complete<br>";
			//loadingText.visible = false;
			
			initUI();
			
		}
		
		/**************************************************** END LISTENERS *************************************************************************/
		
		
		
		public function exitPhase(phaseName:String) {
			trace("Exiting", phaseName, "phase");
			switch (phaseName) {
				case "subs":
					playArea.exitSubstitutionPhase();
				break;
				case "discard":
					playArea.exitDiscardPhase();
				break;
				case "play":
					playArea.exitPlayPhase();
				break;
				case "solve":
					playArea.exitSolvePhase();
				break;
			}
		}
		
		public function ping():void {
			trace("INITIALIZER PINGED");
		}
		
		
		
	}
	
}